<template>
  <div class="check-box">
    <!-- 默认插槽， -->
    <slot></slot>
    <el-checkbox
      v-model="checkAll"
      :indeterminate="isIndeterminate"
      @change="handleCheckAllChange"
      v-if="checkAllBox"
      >全部</el-checkbox
    >
    <el-checkbox-group v-model="checkedOptions" @change="handlecheckedOptionsChange">
      <el-checkbox v-for="item in checkList" :key="item" :label="item" :value="item">{{
        item
      }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
const checkedOptions = ref([])
const isIndeterminate = ref()
const checkAll = ref()
const emit = defineEmits(['checkClick'])
const props = defineProps({
  //    是否展示全选
  checkAllBox: {
    type: Boolean,
    default: false
  },
  //   选择项
  checkList: {
    type: Array,
    default: () => ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen']
  }
})
watch(
  () => props.checkList,
  (newval, oldval) => {
    checkedOptions.value = newval
    checkAll.value = checkedOptions.value.length === props.checkList.length ? true : false
  },
  { deep: true, immediate: true }
)
/**
 * value 返回true或false
 */
const handleCheckAllChange = value => {
  checkedOptions.value = value ? props.checkList : []
  isIndeterminate.value = false
}
/**
 * value 返回一个选中项数组
 */
const handlecheckedOptionsChange = value => {
  let checkedCount = value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < props.checkList.length
  emit('checkClick', value)
}
</script>
<style>
.check-box {
  display: flex;
  align-items: center;
  gap: 30px;
}
</style>
